<?php
declare (strict_types=1);

namespace app\index\controller;

use app\BaseController;
use app\common\model\News as NewsModel;
use think\Request;


class News extends BaseController
{
    //新闻列表
    public function index(Request $request)
    {
        $page = $request->get("page", 1) ?: 1;
        $newsList = NewsModel::select()->toArray();
        //新闻查询
        if (!empty($keyword = $request->get('keyword'))) {
            $newsList = array_filter($newsList, function ($item) use ($keyword) {
                return str_contains($item['title'], $keyword);
            });
        }
        //分页
        $total = count($newsList);
        $totalPage = ceil(count($newsList) / 6);
        $newsList = array_slice($newsList, ($page - 1) * 6, 6);
        return view('news/index', [
            'newsList' => $newsList,
            'total' => $total,
            'totalPage' => $totalPage,
            'page' => $page
        ]);
    }

    //新闻详情
    public function detail($id)
    {
        $news = NewsModel::find($id)->toArray();
        $news['view_times'] += 1;
        unset($news['create_time']);
        NewsModel::update($news);
        return view('news/detail', ['news' => $news]);
    }
}
